package com.project.mall.controller;


import com.project.mall.pojo.Address;
import com.project.mall.pojo.Orders;
import com.project.mall.pojo.User;
import com.project.mall.service.ServiceC;

import com.project.mall.sms.restDemo.client.JsonReqClient;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import java.net.UnknownHostException;

import java.util.*;

import com.alibaba.fastjson.JSONObject;

/**
 * 蔡小凡
 */
@Controller
public class ControllerC {
    @Resource
    private ServiceC service;

    public static final String CAPTCHA_KEY = "session_captcha";

    //输入login跳转到login页面
    @RequestMapping(value="/login",method=RequestMethod.GET)
    public String login(){
        return "before/login";
    }


    /**
     *   提交登录界面，判断登录信息正确则重定向到首页
     *      否则返回登录页面
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(HttpSession session, HttpServletRequest req, Model model/*,@Param("phone")String phone*/) throws UnknownHostException {
        String phone=req.getParameter("phone").trim();
        String password=req.getParameter("password");
        String code=req.getParameter("code").toLowerCase();
        String sesionCode = (String) req.getSession().getAttribute(CAPTCHA_KEY);
       /* model.addAttribute("phone", phone);*/



        /**
         * 验证码校验
         */
        if(code==null){
            System.out.println("验证码不能为空!");
            model.addAttribute("errormess", "验证码不能为空!");
           /* req.setAttribute("errormess","验证码输入错误!");*/
            return "before/login";
        }else if(!code.equals(sesionCode.toLowerCase())){
            System.out.println("验证码输入错误!");
            model.addAttribute("errormess", "验证码输入错误!");
            /*req.setAttribute("errormess","验证码输入错误!");*/
            return "before/login";
        }
        /*
         * 根据用户账户获取用户密码
         */
        System.out.println(password);
        System.out.println(phone);
        User user=service.login(phone);
        if(user==null){

        System.out.println("无该账户");
        model.addAttribute("errormess", "无该账户!");
       /* req.setAttribute("errormess","无该账户!");*/
        return "before/login";
    }else if(phone.equals(user.getPhone())&&password.equals(user.getPassword())){

            System.out.println("登陆成功！！");
            /*service.*/
            session.setAttribute("phone", phone);
            int  userid=service.getIdByPhone(phone);
            session.setAttribute("userid", userid);
            System.out.println(phone);
            return "redirect:/index";
        }else {
            model.addAttribute("errormess", "密码不正确!");
           /* req.setAttribute("errormess","密码不正确!");*/
            System.out.println("密码错误！！！");
            return "before/login";
        }



}


    //生成/更新验证码
    @RequestMapping("captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);

        // 生成图片
        int w = 135, h = 40;
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);

        // 将验证码存储在session以便登录时校验
        session.setAttribute(CAPTCHA_KEY, verifyCode.toLowerCase());
    }


    //------------------------------------------------注册-------------------------------------------
    //输入login跳转到login页面
    @RequestMapping(value="/register",method=RequestMethod.GET)
    public String register(){
        return "before/register";
    }


    @PostMapping("/register")
    public String getAllByUserID(HttpSession session, HttpServletRequest request, Model model){
        String name = request.getParameter("username");
        String phone = request.getParameter("tel");
        String pwd = request.getParameter("password");
        String repwd = request.getParameter("repassword");
        String codes = request.getParameter("codes");
        //获取数据库数据
        User user = new User();
        user.setPhone(phone);
        user.setPassword(pwd);
        user.setOthername(name);
       boolean isAdd = service.addNewUser(user);
        System.out.println("添加用户成功！！！");
        if (isAdd) {
            return "redirect:/login";
        } else {
            return "register";
        }

    }


    //异步手机号确认
    @RequestMapping(value = "/registeres",method = RequestMethod.GET)
    @ResponseBody
    public String register(HttpSession session, HttpServletRequest req, @Param("phone") String phone, Model model) throws UnknownHostException {
        String phones = req.getParameter("phone");
        Map<String, Boolean> map = new HashMap<>();
        //获取数据库数据
            int user=service.register(phone);

            System.out.println(phone);
            System.out.println(user);

            if (user == 0){
                map.put("error",false);

            }else{
                map.put("error",true);
            }
        return JSONObject.toJSONString(map);
    }

    @RequestMapping(value = "/SMS",method = RequestMethod.POST )
    @ResponseBody
    public String get(HttpSession session, HttpServletRequest req, @RequestParam("phone") String phone, Model model){
        System.out.println("进入");

        int code = (int)((Math.random()*9+1)*1000);

        String sid = "578fd2cd587d651e4ab89127beac8f2e";
        String token = "ce1ab6cbcb02c6befcdd387496e1f1de";
        String appid = "b1f23a2b34314474a12d963d3a8398d0";
        String templateid = "499826";
        String param = ""+code;
        String mobile = phone;
        System.out.println(phone);
        String uid = "test";

        Map<String, Boolean> map = new HashMap<>();
        try{

            String result = new JsonReqClient().sendSms(sid, token, appid, templateid, param, mobile, uid);

            System.out.println(result);

            if (result !=null&&"".equals(result)){
                model.addAttribute("code",0);
            }else{
                System.out.println(code);
                model.addAttribute("code",code);


            }
        }catch (Exception e){
            model.addAttribute("code",0);
        }


        return JSONObject.toJSONString(model);

    }


    //------------------------------------------------个人中心-------------------------------------------
   //进入个人中心先判断用户是否登录，
    @GetMapping("/self_info")
    public String getAllByUserID(HttpSession session, HttpServletRequest req,Model model,User user){
        String phone = (String) session.getAttribute("phone");

        if(phone==null){
            return "redirect:/login";
        }else {
             user = service.login(phone);
           model.addAttribute("user",user);

            return "before/self_info";
        }
    }

   @PostMapping("/self_info")
    public String self_info(@Param("phone") String phone,Model model){
        User user = service.getAllbyphone(phone);

        model.addAttribute("user", user);
        return "before/self_info";
    }


      //修改用户信息
    @PostMapping("/sava_self")
    public String save(HttpSession Session, HttpServletRequest request,Model model,User user){
       String phone =(String) Session.getAttribute("phone");

        System.out.println("修改：获取"+phone);
       /* if(phone==null){
            return "redirect:/login";
        }else*/{

        }
        user.getUserid();
        service.updateUser(user);
        System.out.println("修改成功！！！"+user.getUserid()+user.getOthername());
        model.addAttribute("text","修改成功！！！");
        return"before/self_info";
    }


    //------------------------------------------------修改密码-------------------------------------------
//修改密码确认
  @RequestMapping(value = "/pwd",method = RequestMethod.GET)
  @ResponseBody
  public String pwds(HttpSession session, HttpServletRequest req, @Param("pwd") String phone, Model model) throws UnknownHostException {
      System.out.println("进入ajax");
      String pwds = req.getParameter("pwd");
      Map<String, Boolean> map = new HashMap<String, Boolean>();
      //获取数据库数据
      User user = (User) session.getAttribute("user");
      String pwd = user.getPassword();
      System.out.println(pwds);
      System.out.println(pwd);
      if (pwds==null){
          return "redirect:/login";
      }else if (pwds.equals(pwd) ){
          map.put("error",true);

      }else{
          map.put("error",false);
      }
      return JSONObject.toJSONString(map);
  }

  //提交修改密码
  @RequestMapping(value = "/pwd-change",method = RequestMethod.GET)
  public String fromPwdes(HttpSession session, HttpServletRequest req, Model model)  {

      return "before/pwd-change";
  }

    @RequestMapping(value = "/pwd-change",method = RequestMethod.POST)
    public String fromPwd(HttpSession session, HttpServletRequest req, Model model) throws UnknownHostException {
        String pwds = req.getParameter("newpassword");
        User user = (User) session.getAttribute("user");
        String phone = user.getPhone();
        System.out.println("密码修改成功！！！"+phone);
        user.setPassword(pwds);
        service.updatepwd(user);
        return "before/self_info";
    }

    //------------------------------------------------添加收货地址-------------------------------------------

   //判断用户不为空 则跳转到显示地址页面
    @RequestMapping(value = "/user-address",method = RequestMethod.GET)
    public String address(HttpSession session, HttpServletRequest req,Model model){
        String phone = (String) session.getAttribute("phone");
        if (phone==null){
            return "redirect:/login";
        }
        int userids =service.getIdByPhone(phone);

          List<Address> addresses = service.getAdressByuser(userids);

        if(addresses==null){
            return "redirect:/login";
        }else {
            model.addAttribute("address",addresses);
            //由用户信息获取

            return "before/user-address";
        }
    }

    //点击编辑地址详情信息
    @RequestMapping(value = "/updateaddress/{addId}",method = RequestMethod.GET)
    public String updateaddress(HttpSession session, HttpServletRequest req,@PathVariable Integer addId, Model model) throws UnknownHostException {
        String phone = (String) session.getAttribute("phone");
        int userid =service.getIdByPhone(phone);
  /*     address.setUserid(userid);
      address.setAddress1((String) req.getAttribute("addresses"));*/
        int userids =service.getIdByPhone(phone);
        //查询结果返回前台界面
        Address address = service.getaddressAllByAddID(addId);
            model.addAttribute("address",address);
        return "before/update_address";
    }


    //保存用户地址信息
    @RequestMapping(value = "/saveaddress",method = RequestMethod.POST)
    public String saveaddress(Address address) throws UnknownHostException {
        //保存用户信息   1.先获取addid 通过
        System.out.println(address);
        System.out.println(address.getAddId());
        boolean isUpdate = service.updateAddress(address);
        if (isUpdate) {
            return "redirect:/user-address";
        }
        return "before/update_address";
    }

    @RequestMapping(value = "/address2",method = RequestMethod.GET)
    public String address_2(HttpSession session, HttpServletRequest req,Model model) {

            return "before/user-address_2";
        }


        //保存新增加的数据
    @RequestMapping(value = "/add_address",method = RequestMethod.POST)
    public String adress_success(Address address,HttpSession session, HttpServletRequest req, Model model) throws UnknownHostException {
      //添加地址
        String phone =(String) session.getAttribute("phone");
        int userid=service.getIdByPhone(phone);
        if (phone==null){
            return "login";
        }else
        System.out.println(userid);
        address.setUserid(userid);
        service.addAddress(address);
        return "redirect:/user-address";
    }
    //------------------------------------------------我的订单-------------------------------------------
    @RequestMapping(value = "/myorder",method = RequestMethod.GET)
    public String myorders(HttpSession session, HttpServletRequest req,Model model,Orders orders) {
        String phone =(String) session.getAttribute("phone");
        int userid=service.getIdByPhone(phone);
        if (phone==null){
            return "login";
        }else{
            List<Orders> kkk= service.getSelfrderby(userid);

            System.out.println(kkk);

            model.addAttribute("orders",kkk);
        }
        return "before/myorder";
    }



 /*   @RequestMapping(value = "/myorder",method = RequestMethod.POST)
    public String myorder(Address address,HttpSession session, HttpServletRequest req, Model model) throws UnknownHostException {

        String phone =(String) session.getAttribute("phone");
        int userid=service.getIdByPhone(phone);
        if (phone==null){
            return "login";
        }else
            System.out.println(userid);
        address.setUserid(userid);
        req.getAttribute("addressName");
        req.getAttribute("addname");
        req.getAttribute("addname");
        req.getAttribute("addname");
        req.getAttribute("addname");
        service.addAddress(address);
        return "redirect:/user-address";
    }*/
 //------------------------------------------------我的订单-------------------------------------------
 @RequestMapping(value = "/comments",method = RequestMethod.GET)
 public String comment(HttpSession session, HttpServletRequest req,Model model,Orders orders) {
     String phone =(String) session.getAttribute("phone");
     int userid=service.getIdByPhone(phone);
     if (phone==null){
         return "login";
     }else{
         List<Orders> kkk= service.getSelfrderby(userid);

         System.out.println(kkk);

         model.addAttribute("orders",kkk);
     }
     return "before/comments";
 }

 /*   @RequestMapping(value = "/commentfrom",method = RequestMethod.POST)
    public String commentfrom(HttpSession session, HttpServletRequest req,Model model,Orders orders) {
        String phone =(String) session.getAttribute("phone");

        int userid=service.getIdByPhone(phone);

        if (phone==null){
            return "login";
        }else{
            List<Orders> kkk= service.getSelfrderby(userid);
            req.getParameter("gid");

            System.out.println(kkk);

            model.addAttribute("orders",kkk);
        }
        return "before/comments";
    }*/
 //------------------------------------------------消息通知-------------------------------------------
 @RequestMapping(value = "/lerts",method = RequestMethod.GET)
 public String lerts(HttpSession session, HttpServletRequest req,Model model,Orders orders) {
     String phone =(String) session.getAttribute("phone");
     int userid=service.getIdByPhone(phone);
     if (phone==null){
         return "login";
     }
     return "before/lerts";
 }


    }




